package com.ruoyi.web.core.config;

import java.util.ArrayList;
import java.util.List;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.ruoyi.common.config.RuoYiConfig;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import io.swagger.v3.oas.annotations.Operation;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.RequestHandler;

/**
 * Swagger configuration for Knife4j.
 *
 * @author ruoyi
 */
@EnableKnife4j
@Configuration
public class SwaggerConfig
{
    @Autowired
    private RuoYiConfig ruoyiConfig;

    @Value("${swagger.enabled}")
    private boolean enabled;

    @Value("${swagger.pathMapping}")
    private String pathMapping;

    @Bean
    public Docket createRestApi()
    {
        String groupName = "default";
        return new Docket(DocumentationType.OAS_30)
                .enable(enabled)
                .apiInfo(apiInfo())
                .select()
                .apis(this::includeAnnotatedHandlers)
                // .apis(RequestHandlerSelectors.basePackage("com.ruoyi.project.tool.swagger"))
                // .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .groupName(groupName)
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                .pathMapping(pathMapping);
    }

    private boolean includeAnnotatedHandlers(RequestHandler handler)
    {
        return handler.findAnnotation(ApiOperation.class).isPresent()
                || handler.findAnnotation(Operation.class).isPresent();
    }

    private List<SecurityScheme> securitySchemes()
    {
        List<SecurityScheme> apiKeyList = new ArrayList<>();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue()));
        return apiKeyList;
    }

    private List<SecurityContext> securityContexts()
    {
        List<SecurityContext> contexts = new ArrayList<>();
        contexts.add(SecurityContext.builder()
                .securityReferences(defaultAuth())
                .operationSelector(operationContext -> {
                    String pattern = operationContext.requestMappingPattern();
                    return pattern != null && !pattern.startsWith("/iot/")
                            && !pattern.startsWith("/system/dict/data/listByDictType")
                            && !pattern.startsWith("/oauth2/codeLogin")
                            && !pattern.startsWith("/area/");
                })
                .build());
        return contexts;
    }

    private List<SecurityReference> defaultAuth()
    {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

    private ApiInfo apiInfo()
    {
        return new ApiInfoBuilder()
                .title("RuoYi Management System API")
                .description("API documentation for RuoYi modules.")
                .contact(new Contact(ruoyiConfig.getName(), null, null))
                .version("Version: " + ruoyiConfig.getVersion())
                .build();
    }
}
